package com.ztf.shopping.web.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ztf.shopping.bean.User;
import com.ztf.shopping.service.UserService;
import com.ztf.shopping.service.imp.UserServiceImp;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        String pwd = request.getParameter("pwd");
        User user = new User(name,pwd);
        ObjectMapper om = new ObjectMapper();
        Map<String,Boolean> map = new HashMap<String,Boolean>();
        /*
        调用服务层，服务层调用dao层，查询数据库
         */
        UserService userService = new UserServiceImp();
        User user1 = userService.loginUser(user);
        if (user1 ==null){
            //登录失败
            map.put("loginUser",false);
            //存在账号未激活问题
        }else {
            //登录成功
            map.put("loginUser",true);
            request.getSession().setAttribute("loginUser",user1);
        }
        om.writeValue(response.getOutputStream(),map);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
